<?php

namespace common\models;

use backend\models\CountryQuery;
use Yii;

/**
 * This is the model class for table "country".
 *
 * @property integer $id
 * @property string $title
 * @property integer $pid
 * @property integer $state
 * @property integer $order
 */
class Country extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'country';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['pid', 'state', 'order'], 'integer'],
            [['order'], 'required'],
            [['title'], 'string', 'max' => 20],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
            'pid' => 'Pid',
            'state' => 'State',
            'order' => 'Order',
        ];
    }

    /*
   *获取省市的名称
    * *传值$_id
    * * @auth ly
     * return string
    */
    public function getName($_id)
    {
        $idName = '';
        if (!empty($_id) && is_numeric($_id)) {
            $res = Country::find()->select(array('title'))->where("id=:id", [':id' => $_id])->asArray()->one();
            if ($res) $idName = $res['title'];
        }
        return $idName;
    }

    /**
     *  id为键，title为值组成的一维数组
     *
     * @return array
     */
    public static function getTitleList()
    {
        $cache = Yii::$app->cache;
        $data = $cache->get('country_title');
        if ($data === false) {
            $list = (new \yii\db\Query())
                ->select(['id', 'title'])
                ->from(self::tableName())
                ->all();
            $data = yii\helpers\ArrayHelper::map($list, 'id', 'title');
            $cache->set('country_title', $data, 30 * 24 * 3600);
        }
        return $data;
    }

    /*获取省或市列表 列表 （ly）*/
    public static function getProvince($_id = 0)
    {
        if (is_int($_id)) {
            $data = self::find()->where(['pid' => $_id])->orderBy('order')->asArray()->all();
            return $data;
        }
        return '';
    }

    public static function find()
    {
        return new CountryQuery(get_called_class());
    }

    public function getProvinces($where = 'pid=0')
    {
        $arr_province = Country::find()->select(['id', 'title'])->where($where)->orderBy('order')->indexBy('id')->asArray()->all();
        unset($arr_province[32], $arr_province[33], $arr_province[34]);
        return $arr_province = \yii\helpers\ArrayHelper::map($arr_province, 'id', 'title');
    }

    public function getProvincesForDropdown($where = "pid=0")
    {
        $arr_province = Country::find()->select("id,title AS name")->where($where)->orderBy('order')->indexBy('id')->asArray()->all();
        unset($arr_province[32], $arr_province[33], $arr_province[34]);
        return $arr_province;
    }

}
